<template>
  <div  class="page-wrap">
    <!-- <pk-header v-if="!counterStore.isMobile"></pk-header> -->
    <div class="page-wrap-layout">
    <div class="page-wrap-header">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/interview' }">{{homeName}}</el-breadcrumb-item>
        <el-breadcrumb-item>候选人明细</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="page-wrap-body">
      <div class="page-wrap-chatbox">
        <el-row>
          <el-col :xl="8" :lg="8" :md="8" :sm="24">
            <div class="page-wrap-cric">
              <c-component></c-component>
            </div>
          </el-col>
          <el-col :xl="16" :lg="16" :md="16" :sm="24">
            <div class="page-wrap-cricbox ml-12 flex-row align-items-center justify-center">
              <d-component></d-component>
            </div>
          </el-col>
        </el-row> 
      </div> 
      <div>
        <el-divider />
      </div>
      <div class="page-wrap-table mt-48">
        <div class="flex-row space-between">
          <div class="flex-row align-items-center">
           <div> 
              <pk-button type="default" @click="allinvite"> 
                <span class="mr-8"><el-icon color="green"><Promotion /></el-icon></span>
                批量邀约
              </pk-button>
            </div>
            <div class="ml-12">
              <pk-button type="default" @click="allChannel"> 
                <span class="mr-8"><el-icon color="green"><Share /></el-icon></span>
                链接分享
              </pk-button>
            </div> 
            <div class="ml-12">
              <el-select
                v-model="state"
                placeholder="选择状态" 
                style="width:100px"
                @change="stateChange"
                clearable
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="ml-12">
              <el-select
                v-model="source"
                placeholder="选择渠道" 
                style="width:100px"
                @change="stateChange"
                clearable
              >
                <el-option
                  v-for="item in channel"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="ml-12 flex-row align-items-center" v-if="counterStore?.userInfo?.organization">
              <span class="pr-8">共计人数: </span>
              <span class="pl-8 red-color bold f-14">
                {{totalqf}}
              </span>

              <span class="pl-8" v-show="curList.length > 0">选择人数: </span>
              <span class="pl-8 red-color bold f-14" v-show="curList.length > 0">
                {{curList.length}}
              </span> 
            </div>
          </div>
          <div class="flex-row align-items-center">
            <div class="mr-12 pointer" @click="getRList">
              <el-icon color="green" size="20"><RefreshRight /></el-icon>
            </div>
            <div>
              <pk-button type="default" @click="isExport=true">
                <span class="mr-8"><el-icon color="green"><Plus /></el-icon></span>
              批量导入</pk-button>
            </div>
            <div class="ml-12">
              <pk-button type="default" @click="setAdd()">
                <span class="mr-8"><el-icon color="green"><Plus /></el-icon></span>
              新增一条</pk-button>
            </div>
          </div>
        </div>
        <div class="mt-12" style="width: 100%;">
          <pk-table :tableConfig="tableConfig" :loading="loading" :data="tableData" :limit="50" :total="total" @onSize="onSize" @handleSelectionChange="handleSelectionChange">
           
            
            <template #mianshistatus="{row}">
              <div class="flex-row"> 
                <div v-if="row.interview_list && row.interview_list.length > 0" class="basegColor pointer" >
                  <el-popover
                    class="box-item"
                    title=""
                    content=""
                    placement="bottom"
                    width="250"
                  >
                    <template #default> 
                      <div>
                        <step-component :data="row.interview_list" @reset="onReset"/> 
                      </div>
                    </template>
                    <template #reference>
                      <!-- <el-icon><View /></el-icon> -->
                      <el-button type="text" :icon="View">查看明细</el-button>
                    </template>
                  </el-popover>
                  <!-- <div @click="handlerInter(row)">查看明细</div>   -->
                </div>
                <div v-else-if="row.interview_list && row.interview_list.length < 1 && row.original_userid">
                  <el-button type="text" :icon="Promotion" @click="setSideDialog(row)">站内邀约</el-button>
                </div>
                <div v-else>--</div>
              </div>
            </template>
            <template #channel="{row}">
              <div class="flex-row">
                <el-button type="text" v-if="row.source == 'import'">外部导入</el-button>
                <el-button type="text" v-if="row.source == 'add'">手动新增</el-button>
                <el-button type="text" v-if="row.source == 'share'">链接分享</el-button>
              </div>
            </template>
            <template #state="{row}">
              <div class="flex-row">
                <div v-if="row.state == 0" class="red-color">待邀约</div>
                <div v-if="row.state == 1" class="color-org">待面试</div>
                <div v-if="row.state == 2" class="basegColor">已面试</div>
              </div>
            </template>
            <template #recommendation="{row}">
              <div class="flex-row">
                <div v-if="row.recommendation==null">--</div>
                <div v-else><pk-rate :data="row.recommendation"></pk-rate></div> 
              </div>
            </template>
            <template #result="{row}">
              <div class="flex-row">
                {{row.match_score || '--'}}
              </div>
            </template> 
            <template #options="{row}">
              <div class="flex-row">
                <div><pk-button type="danger" size="small" @click="handlerdel(row)">删除</pk-button></div>
                <div class="ml-8"><pk-button type="success" size="small" @click="setIsAdd(row)">编辑</pk-button></div>
                <!-- <div class="ml-4"><pk-button type="default" v-if="row.state == 2" size="small" @click="handlerInter(row)">面试评语</pk-button>
                </div> -->
              </div>
            </template>
          </pk-table>
        </div>
      </div>
    </div>
  </div>
  <add-component v-if="isAdd" @onClose="isAdd=false" @confirm="confirmAdd" :data="curData"></add-component>
  <export-component v-if="isExport" @onClose="onClose"></export-component>
  <dialog-component v-if="isDialog" @onClose="isDialog=false" :jobName="homeName" :data="curList" @confirm="confirm"></dialog-component>
  <sidedialog-component v-if="isSideDialog" @onClose="isSideDialog=false" :jobName="homeName" :data="curSideList" @confirm="confirm"></sidedialog-component>
  <channeldialog-component v-if="isChannelDialog" @onClose="isChannelDialog=false" :jobName="homeName" :jobId="jobId" :data="curList" @confirm="confirm"></channeldialog-component>
</div>
</template>

<script setup> 
import { ArrowRight, RefreshRight, Plus, Promotion, View, Share } from '@element-plus/icons-vue'
// import pkHeader from '@/components/header/header.vue'
import stepComponent from './component/step.vue'
import pkButton from '@/components/pkui/pkbutton/pkbutton.vue'
import pkTable from '@/components/pkui/pktable/pktable.vue'
import pkRate from '@/components/pkui/pkrate/pkrate.vue'
import cComponent from './component/c.vue'
import dComponent from './component/d.vue'
import exportComponent from './component/export.vue'
import dialogComponent from './component/dialog.vue'
import sidedialogComponent from './component/sidedialog.vue' 
import channeldialogComponent from './component/channeldialog.vue'
import addComponent from './component/add.vue'
import { onMounted, ref, reactive, computed } from 'vue';
import { useSideStore } from '@/store/state'
import { useRoute, useRouter } from 'vue-router'
import { getUserInfo,candidateDelete, candidateGetPageList } from '@/api/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { qffn } from '@/utils/utils' 
import { getToken, setKeyItem, getKeyUserInfo} from '@/utils/auth'
import { Toast } from '@/utils/vant'
const counterStore = useSideStore()
const homeName = ref()
const route = useRoute()
const router = useRouter()
const isAdd = ref(false)
const page = ref(1)
const total = ref(0)
const totalqf = ref(0)
const isExport = ref(false)
const isDialog = ref(false)
const isSideDialog = ref(false)
const isChannelDialog = ref(false)
const curList = ref([])
const curSideList = ref([])
const tableData = ref([])
const loading = ref(false)
const userInfoData = ref({})
const curData = ref({})
const state = ref('')
const source = ref('')
const options = ref([
  { value: 0, label: '待邀约' },
  { value: 1, label: '待面试' },
  { value: 2, label: '已面试' }
])

const channel = ref([
  { value: 'import', label: '外部导入' },
  { value: 'add', label: '手动新增' },
  { value: 'share', label: '链接分享' }
])

const sideView = ref({})


const tableConfig = reactive([
  {
    type: 'selection'
  },
  {
    label: '序号',
    prop: 'index',
    width: '60px'
  },
  {
    label: '姓名',
    prop: 'fullname',
    minWidth: '50px'
  },
  {
    label: '手机号',
    prop: 'phone',
    width: '160px'
  },
  {
    label: '邮箱',
    prop: 'email',
    width: '220px',
  },
  {
    label: '来源渠道',
    type: 'slot',
    slotName: 'channel',
    prop: 'channel',
    width: '100px'
  },
  {
    label: '状态',
    type: 'slot',
    slotName: 'state',
    prop: 'state'
  },
  {
    label: '邀约明细',
    type: 'slot',
    slotName: 'mianshistatus',
    prop: 'mianshistatus',
    width: 120
  }, 
  {
    label: '推荐指数',
    type: 'slot',
    slotName: 'recommendation',
    width: 150
  },
  {
    label: '匹配度',
    type: 'slot',
    slotName: 'result',
    width: '80px'
  },
  {
    label: '操作',
    type: 'slot',
    slotName: 'options',
    width: '150px',
    fixed: 'right'
  }
])

const jobName = ref("")
const jobId = ref("")
const pageTotal = computed(() => {
  return counterStore?.userInfo?.organization?.employee?.quota - counterStore?.userInfo?.organization?.employee?.usage
})

const handlerdel = (row) => {
  ElMessageBox.confirm(
    '确定要删除？',
    '',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    candidateDelete({
      candidate_id: row.candidate_id
    }).then(res => {
      getList()
    })
  })
}

const allChannel = () => {
  // if (curList.value.length < 1) {
  //   Toast('候选人没有选择')
  //   return
  // }
  
  // if (pageTotal.value < 1) {
  //   Toast('邀约剩余次数必须大于1')
  //   return
  // }
  // if(curList.value.length > pageTotal.value) {
  //   Toast('选择候选人数量大于邀约剩余次数，请调整一下')
  //   return
  // }
  isChannelDialog.value = true

}

const allinvite = () => {
  if (curList.value.length < 1) {
    Toast('候选人没有选择')
    return
  }
  
  if (pageTotal.value < 1) {
    Toast('邀约剩余次数必须大于1')
    return
  }
  if(curList.value.length > pageTotal.value) {
    Toast('选择候选人数量大于邀约剩余次数，请调整一下')
    return
  }
  isDialog.value = true
}

const getInit = () => {
  const { id, name} = route.params
  homeName.value  = name
}

const onClose = (e) => {
  isExport.value = false
  if(e) {
    window.location.reload()
  }
}

const handleSelectionChange = (e) => {
  curList.value = e
}

const setIsAdd = (e) => {
  curData.value = e
  isAdd.value = true
}

const confirm = () => {
  isDialog.value = false
  isSideDialog.value = false
  getUserInfoItem()
  getList()
}

const setAdd = () => {
  curData.value = {}
  isAdd.value = true
}

const confirmAdd = () => {
  isAdd.value = false
  getUserInfoItem()
  getList()
}


const getUserInfoItem = () => {
  console.log('-----getUserInfoItem--------------')
  getUserInfo().then(res => {
    if (res.code == 1000 ) {
      userInfoData.value = res.data
      setKeyItem("userInfo", JSON.stringify(res.data)) 
      counterStore.SETUSERINFO(res.data)
    }
  })
}

const onSize = (e) => {
  page.value = e.page
  getList()
}

const onReset = () => {
  getList()
}

// 刷新
const getRList = () => {
  tableData.value = []
  getList()
}

const stateChange = () => {
  getList()
}

const getList = () => {
  const { id } = route.params
  jobId.value = id
  loading.value = true
  candidateGetPageList({
    page: page.value,
    job_id: id,
    state: state.value,
    source: source.value
  }).then(res => {
    total.value = res.data.total
    totalqf.value = qffn(res.data.total)
    tableData.value = res.data.list.map((item, index) => {
      return {
        ...item,
        index: index + 1
      }
    })
    setTimeout(() => {
      loading.value = false
    }, 500)
  }).catch(err => {
    loading.value = false
  })
}

const handlerInter = (e) => {
  router.push({
    path: `/candidates/report/${e.candidate_id}`
  })
}

const setSideDialog = (e) => {
  sideView.value = e;
  curSideList.value = [e]
  isSideDialog.value = true
}

onMounted(() => {
  getInit()
  getList() 
  const useinfo = getKeyUserInfo() ? JSON.parse(getKeyUserInfo()) : {}
  counterStore.SETUSERINFO(useinfo)
})
</script>

<style lang="scss" scoped>
.page-wrap{
  width: 100%;
  background: #fff;
  height: 100vh;
  overflow-y: auto;
  display: flex;
  &-layout{
    width: 996px;
    margin: 0 auto;
    padding-top: 60px;
  }
  &-header{
    padding: 12px 0;
  }
  &-chatbox{
    font-size: 12px;
  }
  &-cric{
    // border: #000 1px solid;
  }
  &-table{
    font-size: 12px;
    width: 996px; 
  }
  &-cricbox{
    display: flex;
  }
}
@media screen and (max-width: 996px) {
  .page-wrap{
    &-layout{
      width: 100%!important;
      margin: 0 auto;
    }
  }
}
</style>